package com.zan.filter;

import com.alibaba.fastjson.JSON;
import com.zan.entity.LoginUser;
import com.zan.utils.JwtUtils;
import com.zan.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author Zan
 * @Date 2023/10/17 15:13
 * @Description : JWT认证过滤器 - 用户信息从redis去拿，然后进行认证
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // token没有，直接放行即可
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token获取其中的userId
        Claims claims = JwtUtils.parseJWT(token);
        String userId = claims.getSubject();
        // 从redis中获取用户信息
//        LoginUser loginUser = redisCache.getCacheObject(userId);
        // 由于可能fastjson可能解析不出来，因此存入的时候使用字符串的方式存入，取出来的时候转换一下
        LoginUser loginUser = JSON.parseObject(redisCache.getCacheObject(userId), LoginUser.class);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        // 存入SecurityContextHolder，TODO 重点：为后面的过滤器使用
        // 必须要用三个参数的构造器 - 会自动认为你是已认证的状态
        // TODO 第三个参数为权限信息，要将权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
